package com.atguigu.yygh.hosp.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.HttpRequestHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.MD5;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.Department;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class ApiUtils {

    private static HospitalSetService hospitalSetService;

    @Autowired
    private HospitalSetService hospitalSetService2;


    @PostConstruct
    public void beforeInit(){
        hospitalSetService = hospitalSetService2;
    }
    //根据request里的map转换成我们要的map
    static public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(parameterMap);
        return paramMap;
    }

    //检查签名
    static public void checkSign(Map<String, Object> paramMap) {
        //获取签名
        String sign = (String) paramMap.get("sign");
        //获取编码
        String hoscode = (String) paramMap.get("hoscode");
        String signKey = hospitalSetService.getSignKey(hoscode);
        String signKeyMd5 = MD5.encrypt(signKey);
        System.out.println(sign + " " + signKeyMd5);
        if (!sign.equals(signKeyMd5)) {
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
    }

    static public Map<String, Object> getMapAndCheckSign(HttpServletRequest request){
        Map<String, Object> map = getMap(request);
        checkSign(map);
        return map;
    }

    static public <T> T mapToClass(Map<String, Object> map, Class<T> clazz) {
        String string = JSONObject.toJSONString(map);
        return JSONObject.parseObject(string, clazz);
    }

}
